Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

[productId].js 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. const Product = require('../../../models/product');
  2. import dbConnect from '../../../utils/helpers/dbHelpers';
  3. const shuffle = function (v) {
  4. //+ Jonas Raoni Soares Silva
  5. //@ http://jsfromhell.com/array/shuffle [rev. #1]
  6. for (
  7. var j, x, i = v.length;
  8. i;
  9. j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x
  10. );
  11. return v;
  12. };
  13. async function handler(req, res) {
  14. const { method } = req;
  15. await dbConnect();
  16. switch (method) {
  17. case 'GET': {
  18. try {
  19. const productId = req.query.productId;
  20. const product = await Product.findOne({ customID: productId });
  21. if (!product) {
  22. throw new Error('The product with this id does not exist!');
  23. }
  24. const similarProducts = await Product.find({
  25. category: product.category,
  26. customID: { $ne: product.customID },
  27. });
  28. const shuffled = similarProducts
  29. .sort(() => 0.5 - Math.random())
  30. .slice(0, 3);
  31. res.status(200).json({
  32. message: 'The product you requested was fetched successfully.',
  33. product,
  34. similarProducts: shuffled,
  35. });
  36. } catch (error) {
  37. res.status(400).json({ message: error.message });
  38. }
  39. break;
  40. }
  41. default:
  42. res.status(405).json({ message: 'Method not allowed' });
  43. break;
  44. }
  45. }
  46. export default handler;